package com.study.zouchao.superproject.qustionadd.presenter;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.IntegerRes;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.widget.Toast;

import com.study.zouchao.superproject.login.model.entity.User;
import com.study.zouchao.superproject.logininterceptor.LoginStatusUtil;
import com.study.zouchao.superproject.qustionadd.contract.IQuestionAddContract;
import com.study.zouchao.superproject.qustionadd.model.QuestionAddModel;
import com.study.zouchao.superproject.qustionadd.model.result.questionadd.QuestionAddResult;
import com.study.zouchao.superproject.qustionadd.model.result.updateimg.QuestionUpdateImgResult;
import com.study.zouchao.superproject.util.BitmapUtil;
import com.study.zouchao.superproject.util.DialogUtil;
import com.study.zouchao.superproject.util.EventBusEvent;
import com.study.zouchao.superproject.util.EventBusEvent_C;
import com.study.zouchao.superproject.util.EventBusUtils;
import com.study.zouchao.superproject.util.FileUtil;
import com.study.zouchao.superproject.util.RandomUtils;
import com.study.zouchao.superproject.util.RegexUtils;
import com.study.zouchao.superproject.util.StringUtils;
import com.study.zouchao.superproject.util.SystemUtils;
import com.study.zouchao.superproject.util.ToastUtils;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.IllegalFormatCodePointException;
import java.util.Map;


import rx.Subscription;
import rx.functions.Action1;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;


/**
 * Created by Administrator on 2017/4/25.
 */

public class QuestionAddPresenter implements IQuestionAddContract.IQuestionAddPresenter {

    private static final String TAG = "QuestionAddP";

    private Context mContext;

    private IQuestionAddContract.IQuestionAddView mView;

    private IQuestionAddContract.IQuestionAddModel mModel;

    private static final int CHOOSE_PICTURE_FROM_DISK = 0;

    private static final int TAKE_PICTURE = 1;

    private static final int CROP_SMALL_PICTURE = 2;

    //图片扩展名
    private static final String IMG_EXPAND_NAME = ".jpg";
    //每次拍照后这个图片都会被替换
    private static Uri mTempUri;
    //打开摄像头拍照后生成的(临时)图片
    private static String TEMP_IMG_NAME = "";
    //上传头像的filename参数（实际上和 TEMP_IMG_NAME一致）
    private String mFilename = "";
    //图片的压缩程度
    private static final int COMPRESS_LEVEL = Luban.FIRST_GEAR;
    //上传图片, 添加问题的 Subscription
    private Subscription mSupUpdateImg, mSupQuestionAdd;

    private String mTagId;

    private static final String REG_TEL = "^1(3[0-9]|4[57]|5[0-35-9]|7[01678]|8[0-9])\\d{8}$";

    public QuestionAddPresenter(Context context, IQuestionAddContract.IQuestionAddView view) {
        mContext = context;
        mView = view;
        init();
    }

    private void init() {
        mModel = new QuestionAddModel();
    }

    @Override
    public AlertDialog getEnsureUploadAlertDialog(String title, String content) {
            return DialogUtil.showAlertDialog(mContext, title,
                    content, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mView.startUploadText();
                        }
                    }, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {}
                    });
    }

    @Override
    public void clickChoosePicDialog(int itemIndex) {
        //生成临时 图片 名
        TEMP_IMG_NAME = RandomUtils.getImgFilename(IMG_EXPAND_NAME);
        //生成上传头像参数 filename(就是临时图片名)
        mFilename = TEMP_IMG_NAME;

        switch (itemIndex) {
            case CHOOSE_PICTURE_FROM_DISK:
                clickChoosePictureFromDiskItem();
                break;
            case TAKE_PICTURE:
                clickTakePictureItem();
                break;
        }
    }

    @Override
    public void judgeActivityResult(int requestCode, int resultCode, Intent data) {
        //需要判断一下resultCode，即判断一下是运行时被取消了(back键 )还是运行正常 (Activity.RESULT_OK)
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case CHOOSE_PICTURE_FROM_DISK:
                    prepareUplaodImg(data.getData());
                    break;
                case TAKE_PICTURE:
                    prepareUplaodImg(mTempUri);
                    break;
                case CROP_SMALL_PICTURE:
                    break;
            }
        }
    }

    private User getLoginedUserBean() {
        User userBean = LoginStatusUtil.getLoginDataByBean(mContext);
        //事实上 不可能为空
        if (userBean==null) {
            return null;
        }
        return userBean;
    }

    /*
     *
     *
     *  上传图片部分
     *
     *
     */
    private void prepareUplaodImg(final Uri uri) {
        if (uri == null) {
            ToastUtils.showShort(mContext, "系统异常:选择图片失败、请稍后再试");
            return;
        }
        mView.toggleLoading(true);
        new Thread(new Runnable() {
            @Override
            public void run() {
                compressedBitmap(uri);
            }
        }).start();
    }

    private void compressedBitmap(final Uri uri) {
        String realPath = getRealPathFromURI(uri);
        Luban.get(mContext)
                .load(new File(realPath))//传人要压缩的图片
                .putGear(COMPRESS_LEVEL)      //设定压缩档次，默认三挡
                .setCompressListener(new OnCompressListener() { //设置回调
                    @Override
                    public void onStart() {}
                    @Override
                    public void onSuccess(File file) {
                        successCompressBitmapAndPrepareUpdateImg(file, uri);
//                        mView.toggleLoading(false);
                    }
                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        Toast.makeText(mContext.getApplicationContext(), "图片压缩失败!!!", Toast.LENGTH_SHORT).show();
                        mView.toggleLoading(false);
                    }
                }).launch();    //启动压缩
    }

    private void successCompressBitmapAndPrepareUpdateImg(File file, Uri uri) {
        Log.i("压缩成功", file.getAbsolutePath());
        Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
        try {
            updateImg(bm, uri);
        } catch (IOException e) {
            mView.toggleLoading(false);
            e.printStackTrace();Toast.makeText(mContext.getApplicationContext(), "获取上传信息失败!!!", Toast.LENGTH_SHORT).show();}
    }

    private void updateImg(Bitmap bm, final Uri uri) throws IOException {
        if (bm == null) {
            mView.toggleLoading(false);
            ToastUtils.showShort(mContext.getApplicationContext(), "图片获取失败!!!");
            return;
        }
        Map<String, String> updateImgParams = getUploadImgParams(bm);
        if (updateImgParams == null) {
            mView.toggleLoading(false);
            return;
        }
        mSupUpdateImg = mModel.updateImg(updateImgParams)
                .subscribe(new Action1<QuestionUpdateImgResult>() {
                    @Override
                    public void call(QuestionUpdateImgResult updateImgResult) {
                        judgeUpdateImgResult(updateImgResult, uri);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        throwable.printStackTrace();
                        ToastUtils.showShort(mContext.getApplicationContext(), "图片上传失败!!!!");
                        mView.toggleLoading(false);
                    }
                });
    }

    /**
     * 上传头像成功后 判断 返回结果
     *
     * @param updateImgResult
     */
    private void judgeUpdateImgResult(QuestionUpdateImgResult updateImgResult, Uri uri) {
        switch (updateImgResult.getCode()) {
            case 22001:
                successUploadImgAndInsertImgToWebView(updateImgResult.getData().getImages(), uri);
                ToastUtils.showShort(mContext.getApplicationContext(), "上传图片成功！！");
                break;
            default:
                ToastUtils.showShort(mContext.getApplicationContext(), "上传图片失败、"+updateImgResult.getMessage());
                break;
        }
        mView.toggleLoading(false);
    }

    private void successUploadImgAndInsertImgToWebView(String serverUrl, Uri oldUri) {
        mView.successUpdateImg(serverUrl);
        //运行
    }

    private Map<String, String> getUploadImgParams(Bitmap bm) {
        User userBean = getLoginedUserBean();
        if (userBean == null) return null;
        if (bm == null) return null;
        //转换为二进制图片流
        byte[] bytes = BitmapUtil.getBitmapByte(bm);
        if (!bm.isRecycled()) bm.recycle();
        String base64Img = BitmapUtil.byte2Base64(bytes);
        Map<String, String> params = new HashMap<>();
        params.put("images", base64Img);
        return params;
    }

    /**
     * @param contentUri
     * @return
     */
    private String getRealPathFromURI(Uri contentUri) {
        String res = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = mContext.getContentResolver().query(contentUri, proj, null, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                res = cursor.getString(column_index);
            }
            cursor.close();
        }
        return res;
    }

    /**
     * 从本地图库选择图片
     */
    private void clickChoosePictureFromDiskItem() {
        //选择本地图片
        Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
        //选择文件类型 为图片
        openAlbumIntent.setType("image/*");
        //传入一个请求码
        startActivityForResult(openAlbumIntent, CHOOSE_PICTURE_FROM_DISK);
    }

    /**
     * 直接拍照选择图片
     */
    public void clickTakePictureItem() {
        //先请求摄像头访问权限
        requestCameraPermission();
        //打开照相机直接拍照
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //指定临时照片的保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
        File imgFile = FileUtil.createFile(FileUtil.getSDFile(), TEMP_IMG_NAME);

        if (imgFile == null) {
            Log.d(TAG, "imgFile为null");
            return;
        } else {
            Log.d(TAG, "imgFile不为null");
        }
        //得到当前版本号
        if (SystemUtils.sCurrentSystemVersion < 24) {
            /*
             * Android 7.0以下版本 使用当前方式打开摄像头
             */
            mTempUri = Uri.fromFile(imgFile);
            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mTempUri);
            try {
                startActivityForResult(openCameraIntent, TAKE_PICTURE);
            } catch (Exception e) {
                Log.e(TAG, "缺少摄像头访问权限 ");
                ToastUtils.showLong(mContext, "请打开摄像头访问权限");
                e.printStackTrace();
            }
        } else {
            /*
             * Android 7.0以上版本
             */
            ContentValues contentValues = new ContentValues(1);
            contentValues.put(MediaStore.Images.Media.DATA, imgFile.getAbsolutePath());
//            Uri uri = getContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,contentValues);
            mTempUri = mContext.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mTempUri);
            try {
                startActivityForResult(openCameraIntent, TAKE_PICTURE);
            } catch (Exception e) {
                Log.e(TAG, "缺少摄像头访问权限 ");
                ToastUtils.showLong(mContext, "请打开摄像头访问权限");
                e.printStackTrace();
            }
        }
    }

    /*请求摄像头访问权限*/
    private void requestCameraPermission() {
        /**查询是否存在权限要求SDK23*/
//        int hasCameraPermission = mContext.checkSelfPermission(android.Manifest.permission.CAMERA);
    }

    /*
     *
     *
     * 上传文字(HTML) (问题详情)部分
     *
     *
     */
    //TODO:title content合法判断
    @Override
    public void prepareUploadText(String title, String content, String reward, String rewardPrice, String contact) {
        if (!isValidTitleAndContent(title, content,reward, rewardPrice, contact)) {
//            ToastUtils.showShort(mContext.getApplicationContext(), "标题和内容不得为空");
            return;
        }
        mView.showEnsureAlertDialog();
    }

    private boolean isValidTitleAndContent(String title, String content, String reward, String rewardPrice, String contact) {
        if (!isValidTitle(title)) {
            return false;
        }
        if (!isValidContent(content)) {
            return false;
        }
        if (!isValidContact(contact))
            return false;
        if (!isValidRewardPrice(rewardPrice)) {
            return false;
        }
        if (!isValidReward(reward)) {
            return false;
        }
        return true;
    }

    private boolean isValidTitle(String title) {
        if (StringUtils.isEmpty(title)) {
            mView.showSnackBar("信息格式不正确: 标题不得为空", Snackbar.LENGTH_SHORT);
            return false;
        }
        return true;
    }

    private boolean isValidContent(String content) {
        if (StringUtils.isEmpty(content)) {
            mView.showSnackBar("信息格式不正确: 内容不得为空", Snackbar.LENGTH_SHORT);
            return false;
        }
        return true;
    }

    private boolean isValidReward(String reward) {
        if (StringUtils.isEmpty(reward)) {
            mView.showSnackBar("信息格式不正确: 报酬详情不得为空", Snackbar.LENGTH_SHORT);
            return false;
        }
        return true;
    }

    private boolean isValidRewardPrice(String rewardPrice) {
        if (StringUtils.isEmpty(rewardPrice)) {
            mView.showSnackBar("信息格式不正确: 报酬价格不得为空", Snackbar.LENGTH_SHORT);
            return false;
        }
        int num = 0;
        try {
            num = Integer.valueOf(rewardPrice);
        }catch (Exception e) {
            mView.showSnackBar("信息格式不正确: 报酬价格格式不合法", Snackbar.LENGTH_SHORT);
            return false;
        }
        if (num < 0) {
            mView.showSnackBar("信息格式不正确: 报酬价格不能小于0", Snackbar.LENGTH_SHORT);
            return false;
        }
        //TODO:判断价格是否大于用户余额
        return true;
    }

    private boolean isValidContact(String contact) {
        if (StringUtils.isEmpty(contact)) {
            mView.showSnackBar("信息格式不正确: 联系人不得为空", Snackbar.LENGTH_SHORT);
            return false;
        }
        if (!RegexUtils.isValid(contact, REG_TEL)) {
            mView.showSnackBar("信息格式不正确: 联系人手机号码格式不正确", Snackbar.LENGTH_SHORT);
            return false;
        }
        return true;
    }

    @Override
    public void startUploadText(String title, String content, String reward, String rewardPrice, String contact) {
        mView.toggleLoading(true);

        Map<String, String> questionAddParams = getQuestionAddParams(title, content, reward, Integer.valueOf(rewardPrice), contact);
        if (questionAddParams == null) {
            mView.toggleLoading(false);
            return;
        }
        mSupQuestionAdd = mModel.questionAdd(questionAddParams)
                .subscribe(new Action1<QuestionAddResult>() {
                    @Override
                    public void call(QuestionAddResult questionAddResult) {
                        judgeUploadTextResult(questionAddResult);
                        mView.toggleLoading(false);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        throwable.printStackTrace();
                        ToastUtils.showShort(mContext.getApplicationContext(), "上传失败、请检查网络连接是否正常");
                        mView.toggleLoading(false);
                    }
                });
    }



    private Map<String, String> getQuestionAddParams(String title, String content, String reward, int rewardPrice, String contact) {
        User userBean = getLoginedUserBean();
        if (userBean == null)   return null;
        Map<String, String> params = new HashMap<>();
        params.put("userName",   userBean.getUserName());
        params.put("taskTitle",   title);
        params.put("helpContent", content);
        params.put("reward",   reward);
        params.put("rewardPrice", rewardPrice+"");
        params.put("sponsorContact", contact);
        return params;
    }


    private void judgeUploadTextResult(QuestionAddResult questionAddResult) {
        switch (questionAddResult.getCode()) {
            case 21201:
                successUploadText(questionAddResult);
                EventBusUtils.post(new EventBusEvent(EventBusEvent_C.EVENT_REFRESH_COM_TASK_LIST, null));
                ToastUtils.showShort(mContext.getApplicationContext(), questionAddResult.getMessage());
                break;
            default:
                ToastUtils.showShort(mContext.getApplicationContext(), questionAddResult.getMessage());
                break;
        }
        mView.toggleLoading(false);
    }

    private void successUploadText(QuestionAddResult questionAddResult) {
        finishCurrentActivityAndGoToQuestionDetailActivity();
    }


    private void finishCurrentActivityAndGoToQuestionDetailActivity() {
        mView.finishCurrentActivity();
    }

    /**
     * 选择完图片后返回图片给当前Activity
     */
    private void startActivityForResult(Intent intent, int requestCode) {
        ((Fragment) mView).startActivityForResult(intent, requestCode);
    }

    @Override
    public void cancelUploadProgressDialog() {
        if (mSupUpdateImg!=null && !mSupUpdateImg.isUnsubscribed()) {
            mSupUpdateImg.unsubscribe();
            ToastUtils.showShort(mContext.getApplicationContext(), "取消上传");
        }
        if (mSupQuestionAdd!=null && !mSupQuestionAdd.isUnsubscribed()) {
            mSupQuestionAdd.unsubscribe();
            ToastUtils.showShort(mContext.getApplicationContext(), "取消上传");
        }
    }

    @Override
    public void setTagId(String tagId) {
        mTagId = tagId;
    }

    @Override
    public void onDestoryPresnter() {
        cancelUploadProgressDialog();
    }
}
